package com.xunyji.xunyjitest.comm.util.weixin;

import com.thoughtworks.xstream.XStream;
import com.xunyji.xunyjitest.comm.enums.weixin.MessageTypeEnum;
import com.xunyji.xunyjitest.comm.util.HttpMethodUtils;
import com.xunyji.xunyjitest.comm.util.Md5Utils;
import com.xunyji.xunyjitest.comm.util.TransformUtils;
import com.xunyji.xunyjitest.config.baidu.BaiduBaseConfig;
import com.xunyji.xunyjitest.model.baidu.TransResult;
import com.xunyji.xunyjitest.model.baidu.TranslationResponse;
import com.xunyji.xunyjitest.model.weixin.send.ReplyBaseMessage;
import com.xunyji.xunyjitest.model.weixin.send.ReplyTextMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author AltEnter
 * @create 2019-01-09 22:21
 * @desc 消息封装工具类
 **/
@Component
@Slf4j
public class MessageUtils {

    @Autowired
    private BaiduBaseConfig baiduBaseConfig;

    @Autowired
    private HttpMethodUtils httpMethodUtils;

    /**
     * 封装XML格式的”发送文本消息“之默认回复
     * @param fromUserName 粉丝appId
     * @param toUserName 公众号appId
     * @param content XML格式的字符串
     * @return
     */
    public String initReplyTextMessage(String fromUserName, String toUserName, String content) {
        ReplyTextMessage text = new ReplyTextMessage();
        text.setToUserName(fromUserName);
        text.setFromUserName(toUserName);
        text.setMsgType(MessageTypeEnum.RECEIVE_MESSAGE_TEXT.getType());
        long time = System.currentTimeMillis();
        text.setCreateTime(String.valueOf(time));
        text.setContent("你向公众号发送了：" + content);
        return replyTextMessageToXml(text);
    }

    /**
     * 封装XML格式的”发送文本消息“之翻译结果
     * @param fromUserName
     * @param toUserName
     * @param content
     * @return
     */
    public String initReplyTransTextMessage(String fromUserName, String toUserName, String content) {
        ReplyTextMessage text = new ReplyTextMessage();
        text.setToUserName(fromUserName);
        text.setFromUserName(toUserName);
        text.setMsgType(MessageTypeEnum.RECEIVE_MESSAGE_TEXT.getType());
        long time = System.currentTimeMillis();
        text.setCreateTime(String.valueOf(time));
        text.setContent("翻译结果为：" + content);
        return replyTextMessageToXml(text);
    }

    /**
     * 封装XML格式的”发送文本消息“之菜单信息
     * @param fromUserName
     * @param toUserName
     * @param content
     * @return
     */
    public String initReplyMenuTextMessage(String fromUserName, String toUserName, String content) {
        ReplyTextMessage text = new ReplyTextMessage();
        text.setToUserName(fromUserName);
        text.setFromUserName(toUserName);
        text.setMsgType(MessageTypeEnum.RECEIVE_MESSAGE_TEXT.getType());
        long time = System.currentTimeMillis();
        text.setCreateTime(String.valueOf(time));
        text.setContent(content);
        return replyTextMessageToXml(text);
    }

    /**
     * ReplyTextMessage 转化成 XML
     * @param replyTextMessage
     * @return
     */
    private String replyTextMessageToXml(ReplyTextMessage replyTextMessage) {
        XStream xStream = new XStream();
        xStream.alias("xml", replyTextMessage.getClass());
        return xStream.toXML(replyTextMessage);
    }

    public String firstMenu() {
        StringBuffer sb = new StringBuffer();
        sb.append("重庆是个好地方");
        return sb.toString();
    }

    public String secondMenu() {
        StringBuffer sb = new StringBuffer();
        sb.append("成都是个好地方");
        return sb.toString();
    }

    public String unsubscribeMenu() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("欢迎下次关注《寻渝记》\n");
        return stringBuffer.toString();
    }

    /**
     * 主菜单
     * @return
     */
    public String menuText() {
        StringBuffer sb = new StringBuffer();
        sb.append("欢迎关注《寻渝记》，请按照菜单提示进行操作\n");
        sb.append("1、重庆\n");
        sb.append("2、成都\n");
        sb.append("3、寻渝记\n");
        sb.append("回复？调出此菜单\n");
        return sb.toString();
    }

    public String threeMenu(){
        StringBuffer sb = new StringBuffer();
        sb.append("词组翻译使用指南\n\n");
        sb.append("使用示例：\n");
        sb.append("en翻译足球 -> 表示将'足球'翻译成英文\n");
        sb.append("en翻译中国足球 -> 表示将'中国足球'翻译成英文'\n");
        sb.append("zh翻译football -> 表示将'football'翻译成中文'\n\n");
        sb.append("回复？显示主菜单。");
        return sb.toString();
    }

    /**
     * 发送get请求进行翻译
     * @param query
     * @param from
     * @param to
     * @return
     */
    public String getTransStrResult(String query, String from, String to) throws UnsupportedEncodingException {
        Map<String, String> params = buildParams(query, from, to);
        // 调用自定义的get方法
        String restStr = httpMethodUtils.doGetStrWithMapParamByRestTemplate(baiduBaseConfig.getTranslation().getTransApiHost(), params);
        String result = TransformUtils.unicodeToUtf8(restStr);
        TranslationResponse translationResponse = TransformUtils.parseStr2Object(result, TranslationResponse.class);
        log.info("getTransStrResult - 翻译请求结果为：" + translationResponse.toString());
        TransResult transResult = translationResponse.getTrans_result()[0];
        return String.format("%s -> %s", transResult.getSrc(), transResult.getDst());
        // 调用官方提供的get方法
//        return HttpGet.get(baiduBaseConfig.getTranslation().getTransApiHost(), params);
    }

    public Map<String, String> getTransMapResult(String query, String from, String to) throws UnsupportedEncodingException {
        Map<String, String> params = buildParams(query, from, to);
        // 调用自定义的get方法
        Map<String, String> restMap = httpMethodUtils.doGetMapWithMapByRestTemplate(baiduBaseConfig.getTranslation().getTransApiHost(), params);
        String trans_result = restMap.get("trans_result");
        return restMap;
        // 调用官方提供的get方法
//        return HttpGet.get(baiduBaseConfig.getTranslation().getTransApiHost(), params);
    }

    /**
     * 构建请求参数
     * @param query
     * @param from
     * @param to
     * @return
     */
    private Map<String, String> buildParams(String query, String from, String to) {

        String appid = baiduBaseConfig.getTranslation().getAppId();
        String securityKey = baiduBaseConfig.getTranslation().getSecurityKey();

//        String appid = "20190109000255665";
//        String securityKey = "iNPVhM9qtM3Kb0ZTesI9";

        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        log.info("加密前的签名：" + src);
        String sign = Md5Utils.md5(src);
        params.put("sign", sign);
        log.info("加密后的签名：" + sign);

        return params;
    }



}

